package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.*;

import com.entrogy.utils.SendUtils;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.*;

/** 消息发送接口 控制层
 * @Author 许红松
 * @date 2019/5/30 0030 下午 2:28
 */
@RestController
@Transactional
@RequestMapping(value = "/message")
@Api(description = "对群主管理信息操作的相关接口")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private MessageService messageService;//消息发送service接口
    @Autowired
    private GroupService groupService;//群组servcie接口
    @Autowired
    private UserService userService;//用户service接口
    @Autowired
    private VisitService visitService;//
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private ParentService parentService;
    @Autowired
    private ClassService classService;


    /**
     * 根据选择的类型去查询对应的模板
     * @return
     */
   // @PostMapping("/getTemplateList")
    /*public Result getTemplateList(Integer target){
        Map<String,Object>  map = new HashMap<>();
        if (target! = null && !"".equals(target)){
            map.put("target", target);
        }
        List<MessageTemplate> list = messageService.getMessageTemplateList(map);
        return new Result().getResult(401,"查询成功！",1,list);
    };*/


    /** 根据发送对象 来查询电话集合  如果是年级主任 只有给本年级的人发
     * Type 1: 代表查询家长   2 代表查询教师
     * @param Type
     * @return
     */
    public Result getPhoneList(int  Type){
        Map<String,Object>  map = new HashMap<>();
        if (Type == 1){//代表查询家长

        }
        else if(Type == 2){//查询教师

        }
        return  new Result().getResult(401,"查询成功！",1,"");
    }


    /**
     *   获取选择类型
     * @return
     */
    @ApiOperation(value = "获取选择类型")
    @PostMapping(value = "/getChanggeType")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID",name = "schoolCode",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(value = "2代表教师 1代表家长",name = "target",dataType = "int",paramType = "query",required = false)
    })
    public Result  getChanggeType(Integer target,String schoolCode){
        Map<String,Object>  map=new HashMap<>();
        if (StringUtils.isNoneBlank(schoolCode)){
            map.put("schoolCode",schoolCode);
        }
        map.put("target",target);
        List<Map<String,Object>> list=messageService.getChanggeType(map);
        return new Result().getResult(401,"查询成功！",1,list);
    }

    /**
     * 新增通知发起
     * @return
     */
    @ApiOperation(value = "新增通知发起")
    @PostMapping(value = "/insertMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "微信专用Id",name = "uid",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(value = "2代表教师 1代表家长",name = "target",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(value = "0代表自定义 1代表群组",name = "Type",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(value = "群组id",name = "groupId",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "学校ID,微信可以不传",name = "schoolCode",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "15代表年级主任 16代表班主任 17代表任课老师  101代表点对点发送",name = "sid",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "年级ID/班级id，classId为404时，代表发送给部分家长",name = "classId",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "0-单独微信 1-单独短信 2微信+短信",name = "method",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "内容",name = "message_content",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "教师id，用于点对点发送", name = "teacherIds", dataType = "String", paramType = "query", allowMultiple=true),
    })
    public Result insertMessage(@ModelAttribute @Valid MessageEntity messageEntity, BindingResult bindingResult, String uid, String[] teacherIds, String[] parentIds){
        if (bindingResult.hasErrors()){
            return new Result().getResult(402, bindingResult.getAllErrors().get(0).getDefaultMessage(),2,"");
        }
        // 以下代码用于打印日志
        String target = messageEntity.getTarget() == 2 ? "教师" : "家长";
        String noticeType = messageEntity.getType() == 0 ? "自定义" : "群组";
        String noticePerson = "";
        if (messageEntity.getTarget() == 2){
            switch (messageEntity.getSid()){
                case "15":
                    noticePerson = "年级主任";
                    break;
                case "16":
                    noticePerson = "班主任";
                    break;
                case "17":
                    noticePerson = "任课老师";
                    break;
            }
        }
        String gradeId = messageEntity.getGradeId();
        String classId = messageEntity.getClassId();
        String sendType = "";
        switch (messageEntity.getMethod()){
            case 0:
                sendType = "微信";
                break;
            case 1:
                sendType = "短信";
                break;
            case 2:
                sendType = "微信+短信";
                break;
        }

        Integer schoolCode = null;
        UserEntity userEntity = (UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
        Map<String,Object> map = new HashMap<>();
        if (userEntity != null){
            schoolCode = userEntity.getSchoolCode();
            map.put("schoolCode", schoolCode);
            messageEntity.setSchool_code(schoolCode);
            messageEntity.setTeacher_id(userEntity.getId());
        }else{
            if (uid != null) {
                schoolCode = userService.getSchoolCodeByUserId(uid);
                map.put("schoolCode", schoolCode);
                messageEntity.setSchool_code(schoolCode);
                messageEntity.setTeacher_id(uid);
                userEntity = userService.getUserByUid(uid);
            }
        }

        String messageContent = messageEntity.getMessage_content();
        ClassEntity classById = null;
        if (StringUtils.isNoneBlank(classId)){
            classById = classService.getClassById(Integer.valueOf(classId), schoolCode);
        }
        logger.info("正在进行通知发送=>通知目标：" + target + "| 通知类型：" + noticeType + "| 通知的教师类型：" +
                noticePerson + "| 通知的班级/年级：" + (classById == null ? classId : classById.getClassName())  + "| 通知的方式：" + sendType + "| 通知的内容：" + messageContent);
        // 打印日志代码结束

        // 插入发送的消息记录
        int messageId = messageService.insertMessage(messageEntity);
        // 增加当前学校是否开通试运行的判断
        Integer openStatus = schoolService.getSchoolOpenStatus(schoolCode);
        map.put("openStatus", openStatus);

        if (StringUtils.isNoneBlank(messageEntity.getClassId())){
            map.put("classId",messageEntity.getClassId());
        }
        // 根据template_id  获取发送对象
        Template template = messageService.getTemplateContentById(Integer.parseInt(messageEntity.getTemplate_id()),schoolCode);
        // 向前端返回总计发送的人数
        // 实际发送的人数
        int totalSendPeopleNum = 0;
        int actualSendPeopleNum = 0;
        // 教师
        if(messageEntity.getTarget() == 2){
            // 群组
            if (messageEntity.getType() == 1){
                // 获取群组Id
                String groupId = messageEntity.getGroupId();
                // 根据群组id 获取用户信息
                GroupEntity groupEntity = groupService.getGroupById(Integer.parseInt(groupId));
                List<String> staffIds = Arrays.asList(groupEntity.getStaffList().split(","));
                map.put("ids", staffIds);
                List<Map<String,Object>>  list = messageService.getUsersbyBatchId(map);
                totalSendPeopleNum = list.size();
                for (Map<String,Object> map1 : list) {
                    logger.info("教师姓名：" + map1.get("name") + "教师电话：" + map1.get("mobile"));
                    // 通知发送对象入库
                    String phone = (String) map1.get("mobile");
                    PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(phone);
                    String userId = (String)map1.get("id");
                    sendToPerson(messageEntity.getMethod(),
                            (String) map1.get("name"),
                            phone,
                            template,
                            paramsWeiXin(userEntity.getName(),
                            template.getTemplateContent(),
                            messageEntity.getMessage_content(),
                            String.valueOf(schoolCode)),
                            pubCountEntity,
                            messageEntity.getMessage_content(), messageId, userId);
                }
            }
            else if(messageEntity.getType() == 0){//自定义
              //获取发送对象
                if ("15".equals(messageEntity.getSid()) || "16".equals(messageEntity.getSid()) || "17".equals(messageEntity.getSid())){// 15年级主任  16班主任  19教职员工
                   //根据传递过来的classId  查询相应的人员
                    map.put("sid", messageEntity.getSid());
                    List<UserEntity> list = messageService.getpTypeList(map);
                    //发送消息接口接入
                    totalSendPeopleNum = list.size();
                    for (UserEntity userEntity1 : list ) {
                        logger.info("教师姓名：" + userEntity1.getName() + "教师电话：" + userEntity1.getMobile());
                        PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(userEntity1.getMobile());
                        sendToPerson(messageEntity.getMethod(),
                                userEntity1.getName(),
                                userEntity1.getMobile(),
                                template,
                                paramsWeiXin(userEntity.getName(),template.getTemplateContent(),messageEntity.getMessage_content(), String.valueOf(messageEntity.getSchool_code())),
                                pubCountEntity,messageEntity.getMessage_content(), messageId, userEntity1.getId());
                    }
                }else if ("101".equals(messageEntity.getSid())){ // 教师点对点发送通知
                    totalSendPeopleNum = teacherIds.length;
                    if (teacherIds.length > 0){
                        // 去重
                        List<String> teacherIdList = Arrays.asList(teacherIds);
                        Set<String> teacherIdSet = new HashSet<>(teacherIdList);
                        logger.info("正在进行教师点对点发送，教师id集合为=》" + teacherIdSet);
                        for (String teacherId : teacherIdSet) {
                            UserEntity userEntity1 = userService.getUserByUid(teacherId);
                            PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(userEntity1.getMobile());
                            sendToPerson(messageEntity.getMethod(),
                                    userEntity1.getName(),
                                    userEntity1.getMobile(),
                                    template,
                                    paramsWeiXin(userEntity.getName(),
                                            template.getTemplateContent(),
                                            messageEntity.getMessage_content(), String.valueOf(messageEntity.getSchool_code())),
                                    pubCountEntity,
                                    messageEntity.getMessage_content(), messageId, teacherId);
                        }
                    }else {
                        return new Result().getResult(402,"请选择教师后再发送！",2,"");
                    }
                }
            }
        }else{
          //家长时
            //群组
            if (messageEntity.getType()==1){
                // 获取群组Id
                String groupId = messageEntity.getGroupId();
                // 根据群组id 获取用户信息
                GroupEntity groupEntity = groupService.getGroupById(Integer.parseInt(groupId));
                List<String> ids = Arrays.asList(groupEntity.getStaffList().split(","));
                totalSendPeopleNum = ids.size();
                map.put("ids", ids);
                List<ParentVisitorEntity> parentsbyBatchList = messageService.getParentsbyBatchId(map);
                // 发送消息接口接入
                logger.info("家长群组人数：" + parentsbyBatchList.size());
                // 处于未开通试运行状态的话，需要判断能不能给该家长发送消息
                actualSendPeopleNum = ids.size();
                for (ParentVisitorEntity parentVisitorEntity: parentsbyBatchList ) {
                    if (!canSend(parentVisitorEntity.getParentVisitorId(), openStatus)){
                        actualSendPeopleNum--;
                        continue;
                    }
                    PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(parentVisitorEntity.getParentVisitorPhone());
                    sendToPerson(messageEntity.getMethod(), parentVisitorEntity.getParentVisitorName(),
                            parentVisitorEntity.getParentVisitorPhone(),template,
                            paramsWeiXin(userEntity.getName(),template.getTemplateContent(),
                            messageEntity.getMessage_content(),
                            String.valueOf(messageEntity.getSchool_code())),pubCountEntity,
                            messageEntity.getMessage_content(), messageId, parentVisitorEntity.getParentVisitorId());
                }
            }
            // 自定义
            else{
                map.put("target", messageEntity.getTarget());
                String parentClassId = (String) map.get("classId");
                if ("404".equals(parentClassId)){
                    map.put("parentIds", parentIds);
                }
                List<Map<String, Object>> list = groupService.getParentList(map);
                totalSendPeopleNum = list.size();
                actualSendPeopleNum = list.size();
                logger.info("家长发送人数：" + totalSendPeopleNum);
                for (Map<String, Object> map1 : list) {
                    // 点对点或者自定义的全校发送只要家长有支付记录即可
                    String parentVisitorId = (String)map1.get("parent_visitor_id");
                    if ("404".equals(parentClassId) || "4".equals(parentClassId)){
                        if (!canSend(parentVisitorId, openStatus)){
                            actualSendPeopleNum--;
                            continue;
                        }
                    }else { // 自定义发送需要判断家长在年级和班级的的学生是否有支付记录
                        Integer isGrade = 0;
                        if (parentClassId.substring(4,5).equals("0")){
                            isGrade = 1;
                        }
                        if (!canSendByGradeOrClassId(isGrade, parentClassId, parentVisitorId, openStatus, schoolCode)){
                            actualSendPeopleNum--;
                            continue;
                        }
                    }
                    PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(map1.get("parent_visitor_phone").toString());
                    sendToPerson(messageEntity.getMethod(),
                            map1.get("parent_visitor_name").toString(),
                            map1.get("parent_visitor_phone").toString(),
                            template,
                            paramsWeiXin(userEntity.getName(),
                                    template.getTemplateContent(),
                                    messageEntity.getMessage_content(),
                                    String.valueOf(schoolCode)), pubCountEntity, messageEntity.getMessage_content(), messageId, parentVisitorId);
                }
            }
        }
//        return new Result().getResult(401,"发送成功，总计发送" + totalSendPeopleNum + "人！实际发送" + actualSendPeopleNum + "人！",1,"");
        return new Result().getResult(401,"发送成功，总计发送" + totalSendPeopleNum + "人！",1,"");
    }



    /**
     *  获取年级班级 或者全校 全班等
     * @return
     */
    @GetMapping("/getClassList")
    @ApiOperation(value = "分页获取所有教师")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID",name = "schoolCode",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "是否包含班级 包含不传 不包含传1",name = "parentId",dataType = "String",paramType = "query",required = false)
    })
    public Result getClassList(String schoolCode,String parentId){
        Map<String,Object> map = new HashMap<>();
        if (StringUtils.isNoneBlank(schoolCode)){
            map.put("schoolCode",schoolCode);
        }
        if (StringUtils.isNoneBlank(parentId)){
            map.put("parentId", parentId);
        }
        UserEntity userEntity = (UserEntity) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
        List<Integer> positionIds = new ArrayList<>();
        positionIds.add(8);
        positionIds.add(15);
        positionIds.add(16);
        positionIds.add(17);
        String teacherId = userEntity.getId();
        boolean hasSchoolLevel = positionService.isNotPosition(teacherId, positionIds);
        boolean isGradeLeader = false;
        boolean isClassLeader = false;
        if (!hasSchoolLevel) {
            if (isGradeLeader){
                isGradeLeader = positionService.checkPosition(teacherId, 15);
                map.put("gradeId", userEntity.getGradeId());
            }else {
                isClassLeader = positionService.checkPosition(teacherId, 16);
                if (isClassLeader){
                    map.put("classId", userEntity.getClassId());
                }
            }
        }
        List<ClassEntity> list = messageService.getClassList(map, isClassLeader, isGradeLeader);
        return new Result().getResult(401,"查询成功！",1,list);
    }


    @RequestMapping(value = "/getResult",method = RequestMethod.POST)
    @ApiOperation(value = "分页获取所有小程序发送界面信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "小程序进入ID", name = "uid", dataType = "String", paramType = "query", required = false)
    })
    public Result getResult(String uid){
        Map<String,Object> map = new HashMap<>();
        SmallProgramResult smallProgramResult = new SmallProgramResult();
        if (StringUtils.isNoneBlank(uid)){// 不为空
            UserEntity userEntity = userService.getUserByUid(uid);
            if (userEntity != null){
                map.put("schoolCode", userEntity.getSchoolCode());
                map.put("school_code", userEntity.getSchoolCode());
                // 不同的职位显示范围不一样
                boolean isLifeTeacher = false;
                boolean isCourseTeacher = false;
                List<Integer> positionIdList = positionService.listPositionId(uid);
                for (Integer positionId : positionIdList) {
                    if (positionIdList.size() == 1 && positionId.equals(8)){
                        isLifeTeacher = true;
                    }
                    if (positionIdList.size() == 1 && positionId.equals(17)){
                        isCourseTeacher = true;
                    }
                }
                if (isLifeTeacher || isCourseTeacher){
                    return new Result().getResult(304,"对不起，您没有权限！",2,smallProgramResult);
                }

                // 是否拥有与发全校性通知的职位（除生活老师、保安、年级组长、班主任外均有发全校性通知的权限）
                List<Integer> positionIds = new ArrayList<>();
                positionIds.add(8);
                positionIds.add(15);
                positionIds.add(16);
                positionIds.add(17);
                boolean hasSchoolLevel = positionService.isNotPosition(uid, positionIds);
                boolean isGradeLeader = positionService.checkPosition(uid, 15);
                boolean isClassLeader = positionService.checkPosition(uid, 16);
                if (!hasSchoolLevel) {
                    if (isGradeLeader){
                        map.put("gradeId", userEntity.getGradeId());
                    }else {
                        if (isClassLeader){
                            map.put("classId", userEntity.getClassId());
                        }
                    }
                }
                // 全校包括班级
                List<ClassEntity> list=messageService.getClassList(map, isClassLeader, isGradeLeader);
                // 全校不包括班级
                map.put("parentId","1");
                List<ClassEntity> list1 = messageService.getClassList(map, false, false);
                map.put("type",2);//老师
                List<Map<String,Object>> list3 = messageService.getChanggeType(map);
                map.put("type",1);//家长
                List<Map<String,Object>> list4 = messageService.getChanggeType(map);
                map.put("stype",2);//教师
                List<GroupEntity> groupTeacherList = groupService.getGroupList(map);
                map.put("stype",1);//家长
                List<GroupEntity> groupParentList = groupService.getGroupList(map);
                // 查询
                smallProgramResult.setClassList(list);
                smallProgramResult.setParentMessageList(list4);
                smallProgramResult.setTeacherMessageList(list3);
                smallProgramResult.setClassList1(list1);
                smallProgramResult.setGroupParentList(groupParentList);
                smallProgramResult.setGroupTeacherList(groupTeacherList);
                smallProgramResult.setMessageSendTeacher(JudgmentSend(uid).getMessageSendTeacher());
                smallProgramResult.setMessageSendParent(JudgmentSend(uid).getMessageSendParent());
            }
        }

        return  new Result().getResult(401,"查询成功",1,smallProgramResult);
    }


    @RequestMapping(value = "/getClassTeacherList",method = RequestMethod.POST)
    @ApiOperation(value = "获取 普通教师的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "年级id",name = "grideId",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "班级id",name = "classId",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(value = "学校id",name = "schoolCode",dataType = "String",paramType = "query",required = false)
    })
    public  Result  getClassTeacherList(String grideId,String classId,String schoolCode){
        Map<String,Object> map=new HashMap<>();
        if (StringUtils.isNoneBlank(grideId)){
            map.put("grideId",grideId);
        }
        if (StringUtils.isNoneBlank(classId)){
            map.put("classId",classId);
        }
        if (StringUtils.isNoneBlank(schoolCode)){
            map.put("schoolCode",schoolCode);
        }
       return new Result().getResult(401,"查询成功",1,messageService.getClassTeacherList(map));
    }

    /**
     *   判断发送权限
     * @return
     */
    @RequestMapping(value = "/JudgmentSend",method = RequestMethod.POST)
    @ApiOperation(value = "获取普通教师的数据")
    @ApiImplicitParams({
    @ApiImplicitParam(value = "微信专用Id",name = "uid",dataType = "String",paramType = "query",required = false)
    })
    public SmallProgramResult JudgmentSend(String uid) {
        UserEntity userEntity = (UserEntity) (SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
        StringBuffer messageSendTeacher = new StringBuffer();
        StringBuffer messageSendParent = new StringBuffer();
        if (userEntity != null) {
            List<PositionEntity> positionList = positionService.listTeacherPosition(userEntity.getId());
            // 拼接教师能够发送教师的快捷方式
            for (PositionEntity positionEntity : positionList) {
                messageSendTeacher.append(",").append(positionEntity.getMessageSendTeacher());
                if (positionEntity.getMessageSendParent().equals(1)){
                    // 只需要有一个职位拥有发送给家长的权限的话就行
                    if (messageSendParent.length() == 0){
                        messageSendParent.append("1");
                    }
                }
            }
        } else {
            if (uid != null) {
                List<PositionEntity> positionList = positionService.listTeacherPosition(uid);
                // 拼接教师能够发送教师的快捷方式
                for (PositionEntity positionEntity : positionList) {
                    messageSendTeacher.append(",").append(positionEntity.getMessageSendTeacher());
                    if (positionEntity.getMessageSendParent().equals("1")){
                        // 只需要有一个职位拥有发送给家长的权限的话就行
                        if (messageSendParent.length() == 0){
                            messageSendParent.append("1");
                        }
                    }
                }
            }
        }
        SmallProgramResult smallProgramResult = new SmallProgramResult();
        List<String> messageSendTeacherList = Arrays.asList(messageSendTeacher.toString().substring(1).split(","));
        Set<String> temp = new HashSet<>(messageSendTeacherList);
        messageSendTeacherList = new ArrayList<>(temp);
        messageSendTeacher = new StringBuffer();
        for (String s : messageSendTeacherList) {
            messageSendTeacher.append(",").append(s);
        }
        smallProgramResult.setMessageSendParent(messageSendParent.toString());
        smallProgramResult.setMessageSendTeacher(messageSendTeacher.toString().substring(1));
        return smallProgramResult;
    }

    /**  短信模板
     * @param paramString
     * @param schoolCode
     * @return
     */
   private  String[] paramsWeiXin(String senderName, String tempContent, String paramString, String schoolCode){
       String[] paramsMobile = new String[2];
       paramsMobile[0] = paramString;
       paramsMobile[1] = "";
       // 根据模板id  查询模板内容
       // 拼接参数和通知
       String[] contentArr = tempContent.split("[{]");
       String msgContent = contentArr[0] + paramsMobile[0] + contentArr[1].substring(2) + paramsMobile[1];
       // 填写微信公众号推送参数
       String currentTime = new TimeUtils().getCurrentDateTime();
       String schoolName = schoolService.getSchoolName(Integer.valueOf(schoolCode));
       String[] paramsWeiXin = { "", schoolName, senderName, currentTime, msgContent, "" };
       return paramsWeiXin;
    }

    // 发给一个人
    public void sendToPerson(int method, String name, String phone, Template template,
                             String[] paramsWeiXin, PubCountEntity pubCountEntity, String paramString, int messageId, String userId) {
        String[] paramsMobile = new String[2];
        paramsMobile[0] = paramString;
        paramsMobile[1] = "";
        MessageSendEntity messageSendEntity = new MessageSendEntity();
        messageSendEntity.setMessageId(messageId).setUserId(userId).setSuccess(0);
        if (method == 1 || method == 2) {
            messageSendEntity.setPhone(phone);
            messageSendEntity.setOpenId(null);
            Integer messageRecordId = messageService.insertMessageRecord(messageSendEntity);
            if (phone != null && !phone.equals("") && !phone.equals("0")) {
                logger.info("短信发送:" + phone + name);
                SendUtils.sendByShortMessageWithRecord(phone, paramsMobile, template.getTemplateId(), messageRecordId);
            }
        }
        if (method == 0 || method == 2) {
            if (null != pubCountEntity && !StrUtils.isNullOrEmpty(pubCountEntity.getOpenid())) {
                messageSendEntity.setOpenId(pubCountEntity.getOpenid());
                messageSendEntity.setPhone(null);
                Integer messageRecordId = messageService.insertMessageRecord(messageSendEntity);
                logger.info("平台发送:" + pubCountEntity.getOpenid() + name);
                SendUtils.sendByWeixinWithRecord(pubCountEntity, paramsWeiXin, template.getWeixinTemplateid(), messageRecordId);
            }
        }
    }

    /**
     * 判断能不能给家长发通知（有没有支付记录）
     * @param parentVisitorId
     * @param openStatus
     * @return
     */
    private boolean canSend(String parentVisitorId, Integer openStatus){
        if (openStatus == 1){
            return true;
        }
        // 发送群组\点对点消息只需要判断家长对应的所有孩子有一个已付费即可
        return parentService.judgeParentPayStatusByStudent(parentVisitorId);
    }

    /**
     * 判断是否在所在班级和年级有支付记录
     * @param isGrade
     * @param parentClassId
     * @param parentVisitorId
     * @param openStatus
     * @param schoolCode
     * @return
     */
    private boolean canSendByGradeOrClassId(Integer isGrade, String parentClassId, String parentVisitorId, Integer openStatus, Integer schoolCode) {
        if (openStatus == 1){
            return true;
        }
        return parentService.isPayForGradeOrClass(isGrade, parentClassId, parentVisitorId, schoolCode);
    }


}
